package com.example.flower_shop.controller.admin;

import com.example.flower_shop.dto.ProductDTO;
import com.example.flower_shop.entity.Product;
import com.example.flower_shop.service.ProductService;
import com.example.flower_shop.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/api/admin/products")
@PreAuthorize("hasRole('MERCHANT')")
@Validated
public class ProductManageController {

    @Autowired
    private ProductService productService;

    @GetMapping
    public Result<Page<Product>> getProducts(
            @RequestParam(required = false) String keyword,
            Pageable pageable) {
        return Result.success(productService.findProducts(keyword, pageable));
    }

    @PostMapping
    public Result<Product> createProduct(@Valid @RequestBody ProductDTO productDTO) {
        return Result.success(productService.createProduct(productDTO));
    }

    @PutMapping("/{id}")
    public Result<Product> updateProduct(
            @PathVariable Long id,
            @Valid @RequestBody ProductDTO productDTO) {
        return Result.success(productService.updateProduct(id, productDTO));
    }

    @PutMapping("/{id}/status")
    public Result<Product> updateProductStatus(
            @PathVariable Long id,
            @RequestParam Integer status) {
        return Result.success(productService.updateProductStatus(id, status));
    }

    @PutMapping("/{id}/display")
    public Result<Product> updateProductDisplay(
            @PathVariable Long id,
            @Valid @RequestBody ProductDTO productDTO) {
        return Result.success(productService.updateProductDisplay(id, productDTO));
    }

    @DeleteMapping("/{id}")
    public Result<Void> deleteProduct(@PathVariable Long id) {
        productService.deleteById(id);
        return Result.success(null);
    }
}